package com.lori.netshop.service.imp;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import redis.clients.jedis.JedisCluster;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lori.netshop.mapper.TbUserMapper;
import com.lori.netshop.pojo.TbUser;
import com.lori.netshop.pojo.TbUserExample;
import com.lori.netshop.pojo.TbUserExample.Criteria;
import com.lori.netshop.service.UserService;
import com.lori.netshop.util.NetshopResult;
import com.lori.netshop.util.StringUtil;
/**
 * 用户登录Service
 * @author Administrator
 *
 */
@Service
public class UserServiceimp implements UserService{
	@Autowired
	private TbUserMapper tbUserMapper;
	@Autowired
	private JedisCluster rediscolony;
	@Value("${SSO_REDIS_KEY}")
	private String SSO_REDIS_KEY;
	@Value("${SSO_REDIS_TIME}")
	private int SSO_REDIS_TIME;
	/**
	 * 用户校验
	 */
	@Override
	public NetshopResult checkUser(String param, Integer type) {
		// 校验参数
		if(StringUtil.isEmpty(param)){
			return NetshopResult.build(400, "需要设置参数");
		}
		if(type == null){
			return NetshopResult.build(400, "需要设置参数");
		}
		if(type != 1 && type != 2 && type != 3){
			return NetshopResult.build(400, "参数类型不在范围内");
		}
		//查询数据
		TbUserExample example = new TbUserExample();
		Criteria criteria = example.createCriteria();
		//设置判断条件
		switch (type) {
		case 1:
			criteria.andUsernameEqualTo(param);
			break;
		case 2:
			criteria.andPhoneEqualTo(param);
			break;
		default:
			criteria.andEmailEqualTo(param);
			break;
		}
		List<TbUser> user = tbUserMapper.selectByExample(example);
		if(user != null && user.size() > 0){
			return NetshopResult.ok(false);
		}
		return NetshopResult.ok(true);
	}
	/**
	 * 用户注册
	 */
	@Override
	public NetshopResult registerUser(TbUser user) {
		//密码加密
		user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
		//补全信息
		user.setCreated(new Date());
		user.setUpdated(new Date());
		int insert = tbUserMapper.insert(user);
		if(insert == -1){
			return NetshopResult.build(400, "数据插入失败");
		}else{
			return NetshopResult.ok();
		}
	}
	/**
	 * 用户登录
	 */
	@Override
	public NetshopResult loginUser(String username, String password) {
		//检验数据
		if(StringUtil.isEmpty(username)){
			return NetshopResult.build(400, "用户名不能为空");
		}
		if(StringUtil.isEmpty(password)){
			return NetshopResult.build(400, "密码不能为空");
		}
		//设置查询条件
		TbUserExample example = new TbUserExample();
		Criteria criteria = example.createCriteria();
		criteria.andUsernameEqualTo(username);
		criteria.andPasswordEqualTo(DigestUtils.md5DigestAsHex(password.getBytes()));
		//查询数据
		List<TbUser> userList = tbUserMapper.selectByExample(example);
		//判断是否有值
		if(userList != null && userList.size() > 0){
			TbUser user = userList.get(0);
			//设置密码为空
			user.setPassword("");
			//将数据转换为json
			ObjectMapper mapper = new ObjectMapper();
			String json = "";
			try {
				json = mapper.writeValueAsString(user);
			} catch (JsonProcessingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			//生成token
			String token = UUID.randomUUID().toString();
			//将数据存入redis
			rediscolony.set(SSO_REDIS_KEY + token, json);
			//设置过期时间
			rediscolony.expire(SSO_REDIS_KEY + token, SSO_REDIS_TIME);
			return NetshopResult.ok(token);
		}else{
			return NetshopResult.build(400, "用户名或密码错误");
		}
	}
	/**
	 * 根据token查询数据
	 */
	@Override
	public NetshopResult checkByToken(String token) {
		//从缓存中查询数据
		String json = rediscolony.get(SSO_REDIS_KEY + token);
		//判断是否有数据
		if(!StringUtil.isEmpty(json)){
			//刷新时间
			rediscolony.expire(SSO_REDIS_KEY + token, SSO_REDIS_TIME);
			//转为java数据
			ObjectMapper mapper = new ObjectMapper();
			TbUser user = null;
			try {
				user = mapper.readValue(json, TbUser.class);
			} catch (IOException e) {
				e.printStackTrace();
			}
			return NetshopResult.ok(user);
		}else{
			return NetshopResult.build(400, "无此用户用或者用户时间超时");
		}
	}
	/**
	 * 销毁缓存中的token
	 */
	@Override
	public NetshopResult loginOut(String token) {
		//删除键值
		try {
			rediscolony.del(SSO_REDIS_KEY + token);
			return NetshopResult.ok();
		} catch (Exception e) {
			e.printStackTrace();
			return NetshopResult.build(400, e.toString());
		}
	}

}
